package service

import (
	"context"
	"diygw-ui-go/internal/v1/dao"
	"diygw-ui-go/internal/v1/model/admin"
	"fmt"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"time"
)

type sysRole struct{}

// 对象实例化
func SysRole() *sysRole {
	return &sysRole{}
}

// 获取角色列表不分页
func (s *sysRole) GetList(ctx context.Context, in admin.SysRolelistInput) (out admin.SysRolelistOutput, err error) {
	m := dao.SysRole.Ctx(ctx).OmitEmpty().Where("delete_time is null")
	if in.Status != "" {
		m = m.Where("status =?", in.Status)
	}
	if len(in.RoleIds) > 0 {
		m = m.Where("role_id in (?)", in.RoleIds)
	} else if in.RoleId > 0 {
		m = m.Where("role_id= ?", in.RoleId)
	}
	if err = m.Scan(&out.List); err != nil {
		return
	}
	out.Total, err = m.Count()
	return
}

// 获取角色列表分页
func (s *sysRole) GetListPage(ctx context.Context, in admin.SysRolelistInput) (out admin.SysRolelistOutput, err error) {
	m := dao.SysRole.Ctx(ctx).OmitEmpty().Where("delete_time is null")
	if in.Status != "" {
		m = m.Where("status =?", in.Status)
	}
	if in.RoleId > 0 {
		m = m.Where("role_id= ?", in.RoleId)
	}
	if err = m.Page(in.PageNum, in.PageSize).Scan(&out.List); err != nil {
		return
	}
	out.Total, err = m.Count()
	return
}

// 获取详细信息,缓存10小时
func (s *sysRole) GetOne(ctx context.Context, in admin.SysRoleOneInput) (out admin.SysRoleOneInput, err error) {
	err = dao.SysRole.Ctx(ctx).Cache(gdb.CacheOption{
		Duration: time.Hour * 10,
		Name:     "roleID-" + gconv.String(in.RoleId),
		Force:    false,
	}).Where("role_id", in.RoleId).Scan(&out)
	return
}

// 获取角色权限列表
func (s *sysRole) GetAuths(ctx context.Context, _role_id int64) (out []string, err error) {
	db := g.DB()
	rs, _ := db.GetAll(ctx, fmt.Sprintf("select r.role_name,(select permission from sys_menu where menu_id= m.menu_id and `status`=0 ) as r_permission  from sys_role as r,sys_role_menu as m where m.role_id=r.role_id and r.role_id=%d", _role_id))
	_list := []struct {
		RoleName    string `json:"role_name"`
		RPermission string `json:"r_permission"`
	}{}
	err = rs.Structs(&_list)
	if len(_list) > 0 {
		for _, _item := range _list {
			if _item.RPermission != "" {
				out = append(out, _item.RPermission)
			}
		}
	}
	return
}
